import { constantRoutes } from '@/router'
import Layout from '@/layout'

function importComponent(org) {
  for (let item of org) {
    item.component = item.component == 'Layout' ? Layout : require(`@/views/${item.component}.vue`).default
    if (item.children) importComponent(item.children)
  }
}

const state = {
  routes: [],
  addRoutes: [],
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
}

const actions = {
  async generateRoutes({ commit }, data) {
    try {
      let accessedRoutes = data
      importComponent(accessedRoutes)
      accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
      commit('SET_ROUTES', accessedRoutes)
      return accessedRoutes
    } catch (e) {
      console.log('generateRoutes err:', e)
      return []
    }
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
